<!--  商机响应流程详情-->
<template>
  <div>
    <div v-if="requestError" class="text-c errorPlace">
      <img width="100px" height="100px" :src="require('@/assets/images/pic_neterror.png')" alt="获取数据失败" />
      <div class="color-b font14" style="margin: 10px 0 0 0">
        获取数据失败!
      </div>
      <van-button plain round size="small" color="#7232dd" type="primary" @click="getdetail">点击重试</van-button>
    </div>
    <van-form v-else @submit="submitFromData">
      <div class="mt10" style=" display: flex;border-bottom: 1px solid #ebedf0;">
      <div class="blue_item" />
      <span class="font15" style="display: flex; line-height: 33px;margin-left:5px;  flex:1;">三化预算填报-基础信息</span>
      </div>
      <van-field readonly required name="businessId" :value="fromdata.businessId" label="商机编码：" label-width="5em" />
      <van-field readonly required name="businessName" :value="fromdata.businessName" label="商机名称：" label-width="5em" />
      <van-field readonly required name="projectEstablishNumber" :value="fromdata.projectEstablishNumber" label="项目编号：" label-width="5em" />
      <van-field readonly type="textarea" row="1" autosize required name="projectEstablishName" :value="fromdata.projectEstablishName" label="项目名称：" label-width="5em" />
      <van-field readonly required name="city" :value="fromdata.city" label="地市：" label-width="3em" />
      <van-field readonly required name="counties" :value="fromdata.counties" label="县区：" label-width="3em" />
      <van-field readonly required name="competeType" :value="fromdata.competeType" label="项目竞争方式：" label-width="7em" />
      <van-field readonly required name="applicantName" :value="fromdata.applicantName" label="填报人姓名：" label-width="6em" />
      <van-field readonly required name="applicantPhone" :value="fromdata.applicantPhone" label="填报人电话：" label-width="6em" />
      <van-field readonly required name="isIncludeSolutionValue" :value="fromdata.isIncludeSolution=='1'?'是':'否'" label="是否包含三化解决方案：" label-width="11em" />
      <van-field readonly required name="solutionNumber" :value="fromdata.solutionNumber" label="三化解决方案数量：" label-width="9em" />
      <van-field readonly required name="incomeAmountTotal" :value="fromdata.incomeAmountTotal" label="收入合同含税总金额(万元)：" label-width="13em" />
      <van-field readonly required name="incomeAmountNoTotal" :value="fromdata.incomeAmountNoTotal" label="收入合同不含税总金额(万元)：" label-width="14em" />
      <div class="mt10" style=" display: flex;border-bottom: 1px solid #ebedf0;">
        <div class="blue_item"></div>
        <span class="font15" style="display: flex; line-height: 33px;margin-left:5px;  flex:1;">三化解决方案信息</span>
        <van-button block type="info" style="display: inline-block;width:auto;height: 33px;"
                    native-type="button" @click="choseSH">新增</van-button>
      </div>
      <el-table :data="fromdata.solutionPlanInfoList" border style="width: 100%" show-summary
                @cell-mouse-enter="handleCellEnter"
                @cell-mouse-leave="handleCellLeave"
                :summary-method="getSummaries">
        <el-table-column prop="solutionInfoCode" label="三化解决方案编码" width="140"/>
        <el-table-column prop="solutionInfoName" label="三化解决方案名称" width="110"/>
        <el-table-column
            prop="includeAmount"
            label="三化解决方案收入预算金额(含税,万元)"
            width="110">
          <template slot-scope="scope">
            <el-input-number
                style="width: 90px;"
                v-model="scope.row.includeAmount"
                :min="0"
                :controls="false"
                :precision="2"
                placeholder="请输入内容" @change="includeAmountChange(scope.$index,scope.row.includeAmount)"/>
          </template>
        </el-table-column>
        <el-table-column
            prop="includeAmountNo"
            label="三化解决方案收入预算金额(不含税,万元)"
            width="110">
          <template slot-scope="scope">
            <el-input-number
                style="width: 90px;"
                v-model="scope.row.includeAmountNo"
                :min="0"
                :controls="false"
                :precision="2"
                placeholder="请输入内容" @change="includeAmountNoChange(scope.$index,scope.row.includeAmountNo)"/>
          </template>
        </el-table-column>
        <el-table-column prop="includeAmountRate" label="三化解决方案收入预算金额占比(含税,%)" width="110"/>
        <el-table-column prop="includeAmountNoRate" label="三化解决方案收入预算金额占比(不含税,%)" width="110"/>
        <el-table-column prop="contractNo" label="合同编码" width="110"/>
        <el-table-column label="操作" width="145" >
          <template slot-scope="scope">
            <el-button size="mini" type="normal" @click="handleChange(scope.$index)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="padding-bottom: 60px"> </div>
      <div class="footer">
        <van-button block type="info" native-type="submit" style="display: inline-block;width:100%;border: 0px solid #60a9ec;">保存数据</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { getSrqrRequest, saveSolutionPreAmountInfo } from '@/api/dictapi'
import util from "@/assets/js/public";
import { mapGetters } from "vuex"
import {Dialog, Notify, Toast} from "vant";
import historyAndSuggs from "@/views/srqr/historyAndSuggs.vue"
export default {
  data() {
    return {
      active: 0,
      requestError: false,
      params: this.$route.query,
      showHistory: false,
      fromdata: {},//详情信息
      currentDate: new Date(),
      detailData: {},//详情信息,没啥用，但是服务器递交需要id不得不调用这个接口
      approveList: [],//审批意见列表
      todotype:false,
      toread:false,
      shjjfalistdata: {},
      shglhtlistdata: {},
      seleteRow:""
    }
  },
  computed: {
    ...mapGetters(['user']),
    ...mapGetters(['userinfo']),
  },
  components: {
    historyAndSuggs
  },
  //生命周期--创建完成
  beforeRouteEnter(to, from, next) {
    next(vm => {
      console.log('AA', to, 'AAAA', from);
      // 起草 - 从二级”列表“进来（界面因为保活问题，第二次从”列表“进来的时候 created方法不会重新调用，所以需要确保”列表“进来（或唤醒）时，要刷新起草数据）
      // 通过 `vm` 访问组件实例
      if (from.name === 'drawup_transition_tab') {
        vm.params = to.query;
        vm.setProjectEstablishNumber(to.query.projectEstablishNumber);
      }
    });
  },
  created() {
    this.getdetail();
  },
  activated() {
    if (localStorage.getItem('shjjfalistdata') != '{}' && localStorage.getItem('shjjfalistdata')) {
      this.shjjfalistdata = JSON.parse(localStorage.getItem('shjjfalistdata'))
      if (!this.fromdata.solutionPlanInfoList) {
        this.fromdata.solutionPlanInfoList = []
      }
      this.fromdata.solutionPlanInfoList.push(this.shjjfalistdata)
      this.fromdata = JSON.parse(JSON.stringify(this.fromdata));
      localStorage.setItem('shjjfalistdata', '{}')
    }else if (localStorage.getItem('shglhtlistdata') != '{}' && localStorage.getItem('shglhtlistdata')) {
      console.log("所选择的行数是"+this.seleteRow)
      this.shglhtlistdata = JSON.parse(localStorage.getItem('shglhtlistdata'))
      if (!this.fromdata.solutionPlanInfoList) {
        this.fromdata.solutionPlanInfoList = []
      }
      this.fromdata.solutionPlanInfoList[this.seleteRow].contractNo=this.shglhtlistdata.contractNo
      this.fromdata = JSON.parse(JSON.stringify(this.fromdata));
      localStorage.setItem('shglhtlistdata', '{}')
    }
  },
  //方法调用
  methods: {
    includeAmountChange(index,value){ //对比incomeAmountTotal
      console.log("当前行是"+JSON.stringify(index)+"当前内容是--"+value)
      this.fromdata.solutionPlanInfoList[JSON.stringify(index)].includeAmountRate
          =((value / this.fromdata.incomeAmountTotal)*100).toFixed(2)
    },
    includeAmountNoChange(index,value){ //对比incomeAmountNoTotal
      console.log("当前行是"+JSON.stringify(index)+"当前内容是--"+value)
      this.fromdata.solutionPlanInfoList[JSON.stringify(index)].includeAmountNoRate
          =((value / this.fromdata.incomeAmountNoTotal)*100).toFixed(2)
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计';
          return;
        }else if(index === 2||index === 3){
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] += '';
          } else {
            sums[index] = 'N/A';
          }
        }else {
          sums[index] = '';
        }
      });
      return sums;
    },
    handleCellEnter (row, column, cell, event) {
      console.log("1111111111")
      row.isEdit = true
    },
    /** 鼠标移出cell */
    handleCellLeave (row, column, cell, event) {
      row.isEdit = false
    },
    //返回
    goBack() {
      this.$router.back(-1) //返回上一页
    },
    choseSH() {
      this.$router.push(
          {
            name: 'seletesjlist',
            query: {
              seleteType: 'shjjfa',
              solutionPlanInfoList:this.fromdata.solutionPlanInfoList
            }
          }
      );
    },
    handleChange(index){
      this.seleteRow=index
      console.log("所选择的行数是"+this.seleteRow)
      this.$router.push(
          {
            name: 'seletesjlist',
            query: {
              seleteType: 'shglht',
              projectEstablishNumber:this.params.projectEstablishNumber
            }
          }
      );
    },
    handleDelete(index){
      Dialog.confirm({
        title: '提示',
        message: '确定删除吗？',
      }).then(() => {
        this.fromdata.solutionPlanInfoList.splice(index, 1);
      });
    },
    //请求出错
    onError(result) {
      this.requestError = true;
      Toast.clear();
      Notify(result.message);
    },
    setProjectEstablishNumber(projectEstablishNumber) {
      console.log('XXXXXXXXX', projectEstablishNumber);
      this.params.projectEstablishNumber = projectEstablishNumber;
      this.getdetail()
    },
    //获取详情
    getdetail() {
      Toast.loading({
        message: '加载中',
        forbidClick: false
      });
      getSrqrRequest("solutionPreAmountInfo$api$findInfoByProjectId", Object.assign(this.params, {
        kv: {
          "source": 'MOBILE',
          "projectEstablishNumber": this.params.projectEstablishNumber,
          "currentUserCode": util.encrypt(this.user.userName),
        },
        body:{
          "projectEstablishNumber": this.params.projectEstablishNumber,
        }
      })).then((result) => {
        this.fromdata = {};
        Toast.clear();
        if (!result.data) {
          Notify(result.message);
          return;
        }
        if (result.data.data) {
          this.fromdata = result.data.data;
          if (this.fromdata.solutionPlanInfoList!=null){
            this.fromdata.solutionNumber=this.fromdata.solutionPlanInfoList.length
          }
        }
      })

    },
    //下一步流转
    submitFromData() { //提交流转
      //incomeAmountTotal includeAmount incomeAmountNoTotal includeAmountNo
      let allIncludeAmount = 0;
      let allIncludeAmountNo = 0;
      for(var i=0; i<this.fromdata.solutionPlanInfoList.length; i++){
        if(this.fromdata.solutionPlanInfoList[i].contractNo){
          if(this.fromdata.solutionPlanInfoList[i].includeAmount){
            allIncludeAmount=allIncludeAmount+Number(this.fromdata.solutionPlanInfoList[i].includeAmount)
          }else {
            Notify({ type: 'warning', message: '预算金额不能为空' })
            return;
          }
          if(this.fromdata.solutionPlanInfoList[i].includeAmountNo){
            allIncludeAmountNo=allIncludeAmountNo+Number(this.fromdata.solutionPlanInfoList[i].includeAmountNo)
          }else {
            Notify({ type: 'warning', message: '预算金额不能为空' })
            return;
          }
        }else {
          Notify({ type: 'warning', message: '三化解决方案合同编号不能为空' })
          return;
        }
      }
      if(allIncludeAmount>this.fromdata.incomeAmountTotal){
        Notify({ type: 'warning',
          message: '所有三化解决方案收入预算累计金额（含税）：'+allIncludeAmount
              +'，需小于等于项目收入预算含税金额：'+this.fromdata.incomeAmountTotal+'，请重新填写' })
        return
      }
      if(allIncludeAmountNo>this.fromdata.incomeAmountNoTotal){
        Notify({ type: 'warning',
          message: '所有三化解决方案收入预算累计金额（不含税）：'+allIncludeAmountNo
              +'，需小于等于项目收入预算不含税金额：'+this.fromdata.incomeAmountNoTotal+'，请重新填写' })
        return;
      }
      Toast.loading({
        message: '保存中',
        forbidClick: false
      });
      getSrqrRequest("solutionPreAmountInfo$api$saveSolutionPreAmountInfo", Object.assign(this.params, {
        kv: {
          "source": 'MOBILE',
          "currentUserCode": util.encrypt(this.user.userName),
        },
        body:{
          "solutionInfos": this.fromdata,
          "state": "1"
        }
      })).then((result) => {
        Toast.clear();
        if (!result.data) {
          this.onError(result);
          return;
        }
        Notify({ type: 'success', message: '保存成功' })
        this.$router.replace({ path: '/tabview' });
      })
    },

  }
}
</script>
<style  scoped>
.errorPlace {
  position: absolute;
  margin-top: -80px;
  top: 50%;
  margin-left: -50px;
  left: 50%;
}

.file-list {
  border: 1px solid #60a9ec;
  margin: 5px 10px 5px 10px;
  padding: 5px 0px 5px 0px;
  border-radius: 10px;
}

.label-lesson {
  padding-left: 15px;
  color: #ea0023;
  font-size: 12px;
}
</style>
